/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans  http://continuousphysics.com/Bullet/

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, 
including commercial applications, and to alter it and redistribute it freely, 
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/


///create 125 (5x5x5) dynamic object
#define ARRAY_SIZE_X 8
#define ARRAY_SIZE_Y 1
#define ARRAY_SIZE_Z 8

//maximum number of objects (and allow user to shoot additional boxes)
#define MAX_PROXIES (ARRAY_SIZE_X*ARRAY_SIZE_Y*ARRAY_SIZE_Z + 1024)

///scaling of the objects (0.1 = 20 centimeter boxes )
#define SCALING 1.
#define START_POS_X 0
#define START_POS_Y 0
#define START_POS_Z 0
#define OBJECT_DIAMETER 4.0f

#define NUM_ROW_TILES 4
#define NUM_COL_TILES 4
#define TILE_LENGTH 24.0f

#include "BasicDemo.h"
#include "GlutStuff.h"
///btBulletDynamicsCommon.h is the main Bullet include file, contains most common include files.
#include "btBulletDynamicsCommon.h"

#include <stdio.h> //printf debugging
#include <stdlib.h>
#include <time.h>

int rSign()
{
	return rand() % 2 ? 1 : -1;
}

double random()
{
	return ((double)rand() / RAND_MAX);
}

double getRandomf(double min, double max)
{
	double range = (max - min) + 1.0f;
	return min + range * ((double)rand() / RAND_MAX);
}

void BasicDemo::clientMoveAndDisplay()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 

	//simple dynamics world doesn't handle fixed-time-stepping
	float ms = getDeltaTimeMicroseconds();
	
	///step the simulation
	if (m_dynamicsWorld)
	{
	//	m_dynamicsWorld->stepSimulation(ms / 1000000.f);
		m_dynamicsWorld->stepSimulation(btScalar(1.)/btScalar(30.), 2);
		//optional but useful: debug drawing
		m_dynamicsWorld->debugDrawWorld();

		// Add impulse forces for next run 
		btCollisionObjectArray objs = m_dynamicsWorld->getCollisionObjectArray();
		for(int i = 0; i < m_dynamicsWorld->getNumCollisionObjects(); i++)
		{
			btRigidBody *obj = btRigidBody::upcast(objs[i]);
			obj->applyCentralImpulse(btVector3(
				rSign() * random() * 2.0, 
				0,
				rSign() * random() * 2.0));
		}
	}
		
	renderme(); 

	glFlush();

	swapBuffers();

}



void BasicDemo::displayCallback(void) {

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
	
	renderme();

	//optional but useful: debug drawing to detect problems
	if (m_dynamicsWorld)
		m_dynamicsWorld->debugDrawWorld();

	glFlush();
	swapBuffers();
}





void	BasicDemo::initPhysics()
{
	// seend rand()
	srand(time(0));

	// init Phyiscs
	setTexturing(true);
	setShadows(true);

	setCameraDistance(btScalar(SCALING * 50.));

	///collision configuration contains default setup for memory, collision setup
	m_collisionConfiguration = new btDefaultCollisionConfiguration();
	//m_collisionConfiguration->setConvexConvexMultipointIterations();

	///use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded)
	m_dispatcher = new	btCollisionDispatcher(m_collisionConfiguration);

	m_broadphase = new btDbvtBroadphase();

	///the default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded)
	btSequentialImpulseConstraintSolver* sol = new btSequentialImpulseConstraintSolver;
	m_solver = sol;

	m_dynamicsWorld = new btDiscreteDynamicsWorld(m_dispatcher,m_broadphase,m_solver,m_collisionConfiguration);
	
	m_dynamicsWorld->setGravity(btVector3(0,-10,0));



	///create a few basic rigid bodies
	//We can also use DemoApplication::localCreateRigidBody, but for clarity it is provided here:
	{
	//	btCollisionShape* groundShape = new btBoxShape(btVector3(btScalar(50.),btScalar(50.),btScalar(50.)));
		btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0) , 0);
	
		m_collisionShapes.push_back(groundShape);

		btTransform groundTransform;
		groundTransform.setIdentity();
		groundTransform.setOrigin(btVector3(0, 0, 0));

		btScalar mass(0.);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			groundShape->calculateLocalInertia(mass,localInertia);

		//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
		btDefaultMotionState* myMotionState = new btDefaultMotionState(groundTransform);
		btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,groundShape,localInertia);
		rbInfo.m_friction = 8.0f;
		btRigidBody* body = new btRigidBody(rbInfo);

		//add the body to the dynamics world
		m_dynamicsWorld->addRigidBody(body);
	}

	{
		btCollisionShape *xWallShape = new btBoxShape(btVector3(
			btScalar(TILE_LENGTH * NUM_ROW_TILES / 2), 
			btScalar(5.), 
			btScalar(1.)));
		btCollisionShape *zWallShape = new btBoxShape(btVector3(
			btScalar(1.), 
			btScalar(5.), 
			btScalar(TILE_LENGTH * NUM_COL_TILES / 2)));

		m_collisionShapes.push_back(xWallShape);
		m_collisionShapes.push_back(zWallShape);

		btTransform wallTransform;
		wallTransform.setIdentity();

		btScalar mass(0.);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
		{
			xWallShape->calculateLocalInertia(mass,localInertia);
			zWallShape->calculateLocalInertia(mass,localInertia);
		}

		//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
		for(int i = 0; i < 2; i++)
		{
			btVector3 startPos = (i < 1) ? 
				btVector3(-TILE_LENGTH * NUM_ROW_TILES / 2, 0, 0) : 
				btVector3(TILE_LENGTH * NUM_ROW_TILES / 2, 0, 0);
			wallTransform.setOrigin(startPos);

			btDefaultMotionState* myMotionState = new btDefaultMotionState(wallTransform);
			btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, zWallShape, localInertia);
			btRigidBody* body = new btRigidBody(rbInfo);

			//add the body to the dynamics world
			m_dynamicsWorld->addRigidBody(body);
		}

		//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
		for(int i = 0; i < 2; i++)
		{
			btVector3 startPos = (i < 1) ? 
				btVector3(0, 0, -TILE_LENGTH * NUM_COL_TILES / 2) : 
				btVector3(0, 0, TILE_LENGTH * NUM_COL_TILES / 2);
			wallTransform.setOrigin(startPos);

			btDefaultMotionState* myMotionState = new btDefaultMotionState(wallTransform);
			btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, xWallShape, localInertia);
			btRigidBody* body = new btRigidBody(rbInfo);

			//add the body to the dynamics world
			m_dynamicsWorld->addRigidBody(body);
		}

	}

	{
		//create a few dynamic rigidbodies
		// Re-using the same collision is better for memory usage and performance

		//btCollisionShape* colShape = new btBoxShape(btVector3(SCALING*1,SCALING*1,SCALING*1));
		//btCollisionShape* colShape = new btSphereShape(btScalar(1.));
		//btCollisionShape* colShape = new btCapsuleShape(btScalar(1.), btScalar(.25));
		btCollisionShape* colShape = new btCylinderShape(btVector3(
			OBJECT_DIAMETER / 2, 
			0.5,
			OBJECT_DIAMETER / 2));
		m_collisionShapes.push_back(colShape);

		/// Create Dynamic Objects
		btTransform startTransform;
		startTransform.setIdentity();

		btScalar	mass(1.f);

		//rigidbody is dynamic if and only if mass is non zero, otherwise static
		bool isDynamic = (mass != 0.f);

		btVector3 localInertia(0,0,0);
		if (isDynamic)
			colShape->calculateLocalInertia(mass,localInertia);

		float l = TILE_LENGTH;
		float floorWidth = l * NUM_COL_TILES;
		float floorLength = l * NUM_ROW_TILES;
		float dropletRadius = OBJECT_DIAMETER / 2.0f;
		float posRangeWidth = floorWidth / 2.0f;
		float posRangeLength = floorLength / 2.0f;

		for (int k=0;k<ARRAY_SIZE_Y;k++)
		{
			for (int i=0;i<ARRAY_SIZE_X;i++)
			{
				for(int j = 0;j<ARRAY_SIZE_Z;j++)
				{
					startTransform.setOrigin(SCALING * btVector3(
						getRandomf(-posRangeWidth + dropletRadius, posRangeWidth - dropletRadius),
						0.0f,
						getRandomf(-posRangeLength + dropletRadius, posRangeLength - dropletRadius)));
			
					//using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects
					btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
					btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState,colShape,localInertia);
					rbInfo.m_friction = 0.8f;
					btRigidBody* body = new btRigidBody(rbInfo);
					

					m_dynamicsWorld->addRigidBody(body);
				}
			}
		}
	}


}
void	BasicDemo::clientResetScene()
{
	exitPhysics();
	initPhysics();
}
	

void	BasicDemo::exitPhysics()
{

	//cleanup in the reverse order of creation/initialization

	//remove the rigidbodies from the dynamics world and delete them
	int i;
	for (i=m_dynamicsWorld->getNumCollisionObjects()-1; i>=0 ;i--)
	{
		btCollisionObject* obj = m_dynamicsWorld->getCollisionObjectArray()[i];
		btRigidBody* body = btRigidBody::upcast(obj);
		if (body && body->getMotionState())
		{
			delete body->getMotionState();
		}
		m_dynamicsWorld->removeCollisionObject( obj );
		delete obj;
	}

	//delete collision shapes
	for (int j=0;j<m_collisionShapes.size();j++)
	{
		btCollisionShape* shape = m_collisionShapes[j];
		delete shape;
	}
	m_collisionShapes.clear();

	delete m_dynamicsWorld;
	
	delete m_solver;
	
	delete m_broadphase;
	
	delete m_dispatcher;

	delete m_collisionConfiguration;

	
}




